package com.wrupple.muba.catalogs.client.activity.process.task.impl;

import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.wrupple.muba.catalogs.client.activity.process.CatalogImportActivityProcess.ImportData;
import com.wrupple.muba.catalogs.client.activity.process.task.ImportTask;
import com.wrupple.muba.catalogs.client.module.services.logic.CSVParser;
import com.wrupple.muba.catalogs.client.view.ImportView;
import com.wrupple.muba.catalogs.domain.CatalogProcessDescriptor;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.widget.client.widgets.panels.PanelWithToolbar;
import com.wrupple.muba.widget.client.widgets.toolbar.ActionToolbar;

public class CSVImportTask implements ImportTask {
	
	class ReadValuesAndExit implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			ImportData regreso = readValuesAndExit();
			callback.setResultAndFinish(regreso);
		}
		
	}

	ImportView view;
	CSVParser parser;
	private PanelWithToolbar main;
	private StateTransition<ImportData> callback;
	private CatalogProcessDescriptor parameter;
	
	@Inject
	public CSVImportTask(ImportView view, CSVParser parser) {
		super();
		this.view = view;
		this.parser = parser;
		this.main = new PanelWithToolbar();
		main.getContentContainer().setWidget(view);
	}


	@Override
	public void start(CatalogProcessDescriptor parameter,
			StateTransition<ImportData> onDone, EventBus bus) {
		this.parameter=parameter;
		this.callback=onDone;
	}

	@Override
	public Widget asWidget() {
		return main;
	}


	@Override
	public void setAction(List<? extends HasClickHandlers> a) {
		List<Image> actions = (List<Image>) a;
		actions.get(0).addClickHandler(new ReadValuesAndExit());
		ActionToolbar toolbar = new ActionToolbar();
		toolbar.addActions(actions);
		main.addToolbar(toolbar);
	}


	@Override
	public ImportData readValuesAndExit() {
		String csv = view.getCsv();
		ImportData output = parser.parse(csv);
		output.catalog = parameter.getSelectedType();
		return output;
	}



	
}
